<template>
    <div class="prompt-container">
        <!-- 提示输入卡片 -->
        <el-card class="prompt-card">
            <template #header>
                <div class="card-header">
                    <h2>输入混搭提示</h2>
                    <!-- 添加批量生成控件组 -->
                    <div class="batch-generator">
                        <el-input 
                            v-model="batchSettings.folderPath" 
                            placeholder="文件夹路径"
                            clearable
                            style="width: 400px"
                            size="small"
                            class="batch-input"
                        />
                        <el-input-number 
                            v-model="batchSettings.count" 
                            :min="1" 
                            :max="100"
                            size="small"
                            placeholder="数量"
                            class="batch-input-number"
                        />
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click="generateCustomPaths"
                            :disabled="!batchSettings.folderPath || batchSettings.count < 1"
                        >
                            生成路径
                        </el-button>
                        <!-- 加一个清空按钮 -->
                        <el-button 
                            type="danger" 
                            size="small" 
                            @click="clearCategory"
                            >
                        清空分类
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 现有的提示组内容保持不变 -->
            <div class="prompt-groups">
                <div v-for="(group, index) in displayedPrompts" :key="index" class="prompt-group">
                    <span class="prompt-index">{{ index + 1 }}.</span>
                    <!-- 分类选择 -->
                    <el-select v-model="group.category" placeholder="选择分类" style="width: 150px; margin-right: 10px;"
                        :loading="categoriesLoading" clearable @change="() => handleCategoryChange(index)"
                        :disabled="index > 0 && !isRowEnabled(index)">
                        <!-- 常规分类 -->
                        <el-option v-for="category in normalCategories" :key="category" :value="category" :label="category" />
                        <!-- 自定义分类（绿色） -->
                        <el-option key="自定义" value="自定义" label="自定义" class="custom-category-option">
                            <span class="custom-category">自定义</span>
                        </el-option>
                    </el-select>

                    <!-- 关键词输入框 -->
                    <el-autocomplete v-model="group.text"
                        :fetch-suggestions="(query, cb) => querySearchAsync(query, cb, index)" 
                        placeholder="输入关键词"
                        style="flex-grow: 1; margin-right: 10px;" 
                        :disabled="!group.category || (index > 0 && !isRowEnabled(index))"
                        :trigger-on-focus="!isCustomCategory(group.category)"
                        popper-class="my-autocomplete"
                        @focus="handleFocus(index)"
                        @input="updateValue" 
                        :debounce="300">
                        <template #default="{ item }">
                            <div class="suggestion-item">
                                <div class="value">{{ item.value }}</div>
                            </div>
                        </template>
                    </el-autocomplete>
                    
                    <!-- 时长选择器 - 仅在非自定义分类时显示 -->
                    <div class="duration-selector" v-if="group.category && !isCustomCategory(group.category)">
                        <el-popover
                            placement="bottom"
                            :width="280"
                            trigger="click"
                            popper-class="duration-popover"
                        >
                            <template #reference>
                                <el-button 
                                    size="default" 
                                    :type="hasDuration(group) ? 'primary' : 'default'" 
                                    :icon="Clock"
                                    class="duration-button"
                                >
                                    {{ formatDuration(group.duration) }}
                                </el-button>
                            </template>
                            
                            <div class="duration-picker">
                                <div class="duration-title">视频时长限制</div>
                                <div class="duration-inputs">
                                    <el-input-number 
                                        v-model="group.duration.minutes" 
                                        :min="0"
                                        :max="999"
                                        controls-position="right"
                                        size="small"
                                        placeholder="分"
                                        @change="updateValue" 
                                    />
                                    <span class="duration-separator">:</span>
                                    <el-input-number 
                                        v-model="group.duration.seconds" 
                                        :min="0"
                                        :max="59"
                                        controls-position="right"
                                        size="small"
                                        placeholder="秒"
                                        @change="updateValue" 
                                    />
                                </div>
                                <div class="duration-actions">
                                    <el-button size="small" type="danger" @click="clearDuration(group)">清除</el-button>
                                </div>
                            </div>
                        </el-popover>
                    </div>
                </div>
            </div>

            <!-- 现有的提示信息 -->
            <el-alert title="每行一个提示，系统会根据提示搜索视频并混合" type="info" :closable="false" style="margin-top: 15px;" />
            <el-alert title="单文件夹混搭时， 所有选择的视频，视做放到一个文件夹里，每15个作为1个视频组合，如果不足就会跳过" type="info" :closable="false"  />
        </el-card>
    </div>
</template>

<script>
import { defineComponent, ref, computed, nextTick, reactive } from 'vue';
import mergeService from '@/views/Mergeview/services/mergeService';
import { Clock } from '@element-plus/icons-vue';
import AudioUploader from './AudioUploader.vue';
import { ElMessage } from 'element-plus';

export default defineComponent({
    name: 'PromptInput',

    components: {
        AudioUploader
    },

    props: {
        modelValue: {
            type: Array,
            required: true
        },
        categories: {
            type: Array,
            default: () => []
        },
        categoriesLoading: {
            type: Boolean,
            default: false
        }
    },

    emits: ['update:modelValue'],

    setup(props, { emit }) {
        const keywordLoading = ref(false);
        const activeInputIndex = ref(-1); // 当前聚焦的输入框索引

        // 计算普通分类列表（不包括"自定义"）
        const normalCategories = computed(() => {
            return props.categories.filter(cat => cat !== '自定义');
        });

        // 检查是否为自定义分类
        const isCustomCategory = (category) => {
            return category === '自定义';
        };

        // 确保每个组的duration字段初始化
        const initializeDuration = () => {
            props.modelValue.forEach(group => {
                if (!group.duration) {
                    group.duration = { minutes: 0, seconds: 0 };
                }
            });
        };
        initializeDuration();

        // 计算要显示的行数（已填行 + 一个空行，最多显示5行）
        const displayedPrompts = computed(() => {
            let lastValidIndex = -1;

            // 查找最后一个有效行的索引
            for (let i = 0; i < props.modelValue.length; i++) {
                if (props.modelValue[i].category) {
                    lastValidIndex = i;
                }
            }
            console.log('最后一个有效行索引:', lastValidIndex);
            // 确保所有显示的行都有duration字段
            const displayed = props.modelValue.slice(0, lastValidIndex + 2);
            displayed.forEach(group => {
                if (!group.duration) {
                    group.duration = { minutes: 0, seconds: 0 };
                }
            });
            return displayed;
        });

        // 检查行是否可用（只有前一行有category时，当前行才可用）
        const isRowEnabled = (index) => {
            if (index === 0) return true;
            return props.modelValue[index - 1]?.category ? true : false;
        };

        // 通知父组件值已更新
        const updateValue = () => {
            emit('update:modelValue', [...props.modelValue]);
        };

        // 处理分类变更
        const handleCategoryChange = (index) => {
            // 如果清空了分类，同时清空文本和时长
            if (!props.modelValue[index].category) {
                props.modelValue[index].text = '';
                props.modelValue[index].duration = { minutes: 0, seconds: 0 };
            }

            updateValue();
        };

        // 检查是否有设置时长
        const hasDuration = (group) => {
            if (!group.duration) return false;
            return group.duration.minutes > 0 || group.duration.seconds > 0;
        };

        // 格式化时长显示
        const formatDuration = (duration) => {
            if (!duration) return '时长';

            if (duration.minutes === 0 && duration.seconds === 0) {
                return '时长';
            }

            let result = '';
            if (duration.minutes > 0) {
                result += `${duration.minutes}分`;
            }
            if (duration.seconds > 0) {
                result += `${duration.seconds}秒`;
            }
            return result;
        };

        // 清除时长
        const clearDuration = (group) => {
            if (group.duration) {
                group.duration.minutes = 0;
                group.duration.seconds = 0;
                updateValue();
            }
        };

        // 处理输入框聚焦
        const handleFocus = (index) => {
            activeInputIndex.value = index;
        };

        // 获取关键词建议
        const querySearchAsync = (queryString, callback, index) => {

            // 获取当前行的分类
            const currentCategory = props.modelValue[index].category;

            if (!currentCategory || isCustomCategory(currentCategory)) {
                callback([]);
                return;
            }

            // 调用API获取关键词建议
            fetchKeywordSuggestions(queryString, currentCategory)
                .then(suggestions => {
                    nextTick(() => {
                        callback(suggestions);
                    });
                })
                .catch(() => {
                    callback([]);
                });
        };

        // 从API获取关键词建议
        const fetchKeywordSuggestions = async (query, category) => {
            if (keywordLoading.value) return [];

            try {
                keywordLoading.value = true;
                const response = await mergeService.getKeywordSuggestions(query || '', category);
                
                if (response.success && response.data && Array.isArray(response.data)) {
                    return response.data.map(item => {
                        if (typeof item === 'string') {
                            return { value: item };
                        }
                        return {
                            value: item.keyword || item.text || item.toString()
                        };
                    });
                }
                
                return [];
            } catch (error) {
                console.error('获取关键词建议失败:', error);
                return [];
            } finally {
                keywordLoading.value = false;
            }
        };

        // 批量生成设置
        // 批量生成设置，支持本地存储
        const batchSettings = reactive({
            folderPath: localStorage.getItem('batch_folderPath') || '',
            count: Number(localStorage.getItem('batch_count')) || 5
        });

        const clearCategory = () => {
            emit('update:modelValue', [{ category: '', text: '', duration: { minutes: 0, seconds: 0 } }]);
        };

        // 批量生成自定义路径提示
        const generateCustomPaths = () => {
            if (!batchSettings.folderPath) {
                ElMessage.warning('请输入文件夹路径');
                return;
            }
            
            if (batchSettings.count < 1) {
                ElMessage.warning('请输入有效的数量');
                return;
            }
            
            // 规范化路径格式（移除末尾的斜杠）
            const path = batchSettings.folderPath.replace(/[\/\\]$/, '');
            
            // 计算需要生成的提示行数
            const count = batchSettings.count;
            
            // 准备存储新生成的提示
            const newPrompts = [];
            
            // 生成指定数量的自定义路径提示
            for (let i = 1; i <= count; i++) {
                newPrompts.push({
                    category: '自定义',
                    text: `${path}/${i}`,
                    duration: { minutes: 0, seconds: 0 }
                });
            }
            
            // 更新模型值
            // 首先清除现有的空行
            const nonEmptyPrompts = props.modelValue.filter(p => p.category && p.text);
            
            // 添加新生成的提示
            const updatedPrompts = [...nonEmptyPrompts, ...newPrompts];
            
            // 确保有一个空行在末尾
            updatedPrompts.push({ category: '', text: '', duration: { minutes: 0, seconds: 0 } });
            
            // 通知父组件更新
            emit('update:modelValue', updatedPrompts);
            localStorage.setItem('batch_folderPath', batchSettings.folderPath);
            localStorage.setItem('batch_count', batchSettings.count.toString());
            // 显示成功消息
            ElMessage.success(`成功生成 ${count} 个自定义路径提示`);
        };

        return {
            updateValue,
            querySearchAsync,
            keywordLoading,
            displayedPrompts,
            isRowEnabled,
            handleCategoryChange,
            handleFocus,
            activeInputIndex,
            hasDuration,
            formatDuration,
            clearDuration,
            Clock,  // 图标
            normalCategories, // 普通分类列表
            isCustomCategory, // 判断是否为自定义分类
            batchSettings,
            generateCustomPaths,
            clearCategory,
        };
    }
});
</script>

<style scoped>
.prompt-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.prompt-groups {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.prompt-group {
    display: flex;
    align-items: center;
}

.prompt-index {
    width: 25px;
    font-weight: bold;
}

.suggestion-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.suggestion-item .value {
    text-overflow: ellipsis;
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

/* 自定义分类项样式 */
.custom-category {
    color: #67C23A;
    font-weight: bold;
}

:deep(.el-select-dropdown__item.custom-category-option.selected) {
    color: #67C23A;
}

/* 时长选择器样式 */
.duration-selector {
    margin-left: 5px;
    display: flex;
    align-items: center;
}

.duration-picker {
    padding: 15px;
}

.duration-title {
    font-weight: bold;
    margin-bottom: 10px;
    text-align: center;
}

.duration-inputs {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
    gap: 10px;
}

.duration-inputs .el-input-number {
    width: 100px;
}

.duration-separator {
    font-size: 16px;
    font-weight: bold;
    margin: 0 4px;
}

.duration-actions {
    display: flex;
    justify-content: flex-end;
}

.duration-button {
    min-width: 80px;
}

/* 修复关键词输入框的样式 */
:deep(.el-autocomplete) {
    width: 100%;
}

:deep(.el-autocomplete-suggestion) {
    min-width: 200px !important;
}

:deep(.el-autocomplete-suggestion li) {
    padding: 8px 12px;
}

:deep(.my-autocomplete) {
    z-index: 3000 !important;
}

/* 批量生成控件组样式 */
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.batch-generator {
    display: flex;
    gap: 8px;
    align-items: center;
}

.batch-input {
    width: 180px;
}

.batch-input-number {
    width: 80px;
}

@media (max-width: 768px) {
    .card-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .batch-generator {
        width: 100%;
        margin-top: 10px;
    }
}
</style>